package com.zzu.team.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzu.team.entity.Question;
import com.zzu.team.entity.Result;
import com.zzu.team.entity.ReturnBean;
import com.zzu.team.entity.Tester;
import com.zzu.team.service.QuestionService;
import com.zzu.team.service.ResultService;
import com.zzu.team.service.TesterService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * (Result)表控制层
 *
 * @author makejava
 * @since 2021-11-27 20:35:10
 */
@RestController
@RequestMapping("result")
public class ResultController extends BaseController {

    @Resource
    ResultService resultService;

    @Resource
    QuestionService questionService;

    @Resource
    TesterService testerService;

    @GetMapping("selectAll")
    public ReturnBean<List<Result>> selectAll(Integer page, Integer limit, Result result) {
        ReturnBean<List<Result>> returnBean = new ReturnBean<>();
        returnBean.setCode(0);
        returnBean.setMsg("查询");

        Page<Result> resultPage = new Page<>(page-1, limit);

        Page<Result> res = resultService.page(resultPage, new QueryWrapper<>(result));

        returnBean.setData(res.getRecords());
        returnBean.setCount(res.getTotal());

        return returnBean;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ReturnBean selectOne(@PathVariable Serializable id) {
        Result result = resultService.getById(id);
        return success(result);
    }

    /**
     * 根据用户查询查询
     */
    @GetMapping("selectByTester")
    public ReturnBean selectByTester(@RequestParam("testerId") Integer testerId){
        Object object = selectByTesterId(testerId);
        if (object == null) return fail("该用户未答题");
        else return success(object);
    }




    /**
     * 查询所有用户的性格
     */
    @GetMapping("selectAllTesterCharacter")
    public ReturnBean selectAllTesterCharacter(){
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 查询所有用户
        Page<Tester> pageTester = new Page<>();
        Page<Tester> page1 = testerService.page(pageTester, new QueryWrapper<>(null));
        List<Tester> testers = page1.getRecords();
        for (Tester tester: testers){
            Object object = selectByTesterId(tester.getId());
            if (object != null) {
                Map<String, Object> map1 = (Map<String, Object>) object;
                map1.put("tester_id",tester.getId());
                map1.put("testerPhone", tester.getTestphone());
                map1.put("tester_name", tester.getTestname());
                resultList.add(map1);
            }


        }

        return success(resultList);

    }

    public Object selectByTesterId(Integer testerId){
        Map<String, Object> map = new HashMap<>();
        map.put("tester_id", testerId);
        List<Result> results = resultService.listByMap(map);

        // 如果存在该用户, 并且该用户已经答题
        if (results.size()>0) {
            // 用来存储前15道题A、B、C、D 选项个数 和后15道题 A B C D的选项个数
            int beforeA = 0, beforeB = 0, beforeC = 0, beforeD = 0,
                    afterA = 0, afterB = 0,afterC = 0, afterD = 0;

            // 查询 该用户 全部选择A的题目
            List<Result> resultsA = selectByTesterAndResult(testerId, "A");
            if (resultsA.size() >0 ){
                for (Result result: resultsA){
                    int questionId = result.getQuestionId();
                    Question question = questionService.getById(questionId);
                    // 如果是前15道题
                    if (question.getType() == 1) beforeA += 1;
                    else afterA+=1;
                }
            }


            List<Result> resultsB = selectByTesterAndResult(testerId, "B");
            if (resultsB.size() >0 ) {
                for (Result result : resultsB) {
                    int questionId = result.getQuestionId();
                    Question question = questionService.getById(questionId);
                    // 如果是前15道题
                    if (question.getType() == 1) beforeB += 1;
                    else afterB += 1;
                }
            }

            List<Result> resultsC = selectByTesterAndResult(testerId, "C");
            if (resultsC.size() >0 ) {
                for (Result result : resultsC) {
                    int questionId = result.getQuestionId();
                    Question question = questionService.getById(questionId);
                    // 如果是前15道题
                    if (question.getType() == 1) beforeC += 1;
                    else afterC += 1;
                }
            }

            List<Result> resultsD = selectByTesterAndResult(testerId, "D");
            if (resultsD.size() >0 ) {
                for (Result result : resultsD) {
                    int questionId = result.getQuestionId();
                    Question question = questionService.getById(questionId);
                    // 如果是前15道题
                    if (question.getType() == 1) beforeD += 1;
                    else afterD += 1;
                }
            }

            // mapResult 用来存储性格结果
            Map<String, Object> mapReuslt = new HashMap<>();
            mapReuslt.put("red", beforeA+afterD);
            mapReuslt.put("blue", beforeB+afterC);
            mapReuslt.put("yellow", beforeC+afterB);
            mapReuslt.put("green", beforeD+afterA);

            return mapReuslt;


        }

        // 返回该用户未答题
        return null;
    }


    // 根据用户名和结果查询 Result
    public List<Result> selectByTesterAndResult(Integer testerId, String result) {
        Map<String, Object> map = new HashMap<>();
        map.put("tester_id", testerId);
        map.put("result", result);
        List<Result> results = resultService.listByMap(map);
        return results;
    }


    /**
     * 插入数据
     * @param result
     * @return
     */
    @PostMapping("insert")
    public ReturnBean insert(@RequestBody Result result) {

        boolean save = resultService.save(result);
        if (save) return super.success(result);
        return super.fail(result);
    }

    /**
     * 批量插入
     * @param result
     * @return
     */
    @PostMapping("insertBath")
    public ReturnBean insertBath(@RequestBody Collection<Result> result) {

        for (Result r:result){
            System.out.println(r);
        }

        boolean save = resultService.saveBatch(result);
        if (save) return super.success("提交成功");

        return super.fail("提交失败");
    }


    /**
     * 修改数据
     *
     * @param result 实体对象
     * @return 修改结果
     */
    @PutMapping("update")
    public ReturnBean update(@RequestBody Result result) {
        Map<String, Object> map = new HashMap<>();
        map.put("tester_id", result.getTesterId());
        map.put("question_id", result.getQuestionId());
        List<Result> results = resultService.listByMap(map);

        System.out.println("size:"+results.size());
        boolean update;
        if (results.size()> 0) {
            result.setRid(results.get(0).getRid());
            update = resultService.updateById(result);
        }else{
            update = resultService.updateById(result);
        }

        if (update) return super.success(result);
        else return super.fail(result);
    }

    /**
     * 删除数据
     * 根据问题id批量删除问题
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("deleteByIdList")
    public ReturnBean delete(@RequestParam("idList") List<Long> idList) {
        boolean delete = resultService.removeByIds(idList);
        if (delete) return success(idList);
        else return fail(idList);
    }

    /**
     * 根据问题id删除一个问题
     * @param id
     * @return
     */
    @DeleteMapping("deleteById")
    public ReturnBean delete(@RequestParam("id")Integer id) {
        boolean delete = resultService.removeById(id);
        if (delete) return success(resultService.getById(id));
        return fail(resultService.getById(id));
    }
}

